package top.majuan.study.study.servlet.software;

import top.majuan.study.study.dao.TbDeptDAO;
import top.majuan.study.study.dao.TbEmployeeDAO;
import top.majuan.study.study.dao.TbsoftwareDAO;
import top.majuan.study.study.dao.TbsoftwaretypeDAO;
import top.majuan.study.study.entity.*;
import top.majuan.study.study.util.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "softwareadd", urlPatterns = "/software/add.action")
public class AddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        text/plain
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();

        try {
            Integer type_id = Integer.parseInt(req.getParameter("type_id"));
            String software_name = req.getParameter("software_name");
            String description = req.getParameter("description");
            String vendor = req.getParameter("vendor");

            Tbsoftwaretype type = TbsoftwaretypeDAO.queryById(type_id);
            if (type == null) {
                Result<String> result = Result.fail("软件不存在", null);
                writer.println(JsonUtils.stringify(result));
                return;
            }
            Tbsoftware software = new Tbsoftware();
            software.setType_id(type_id.toString());
            software.setSoftware_name(software_name);
            software.setDescription(description);
            software.setVendor(vendor);
            int i = TbsoftwareDAO.insert(software);
            if (i==1) {
                Result<String> result = Result.success("添加成功", null);
                writer.println(JsonUtils.stringify(result));
            } else {
                Result<String> result = Result.fail("添加失败", null);
                writer.println(JsonUtils.stringify(result));
            }
        } catch (Exception e) {
            e.printStackTrace();
            Result<String> result = Result.fail("添加发生错误", null);
            writer.println(JsonUtils.stringify(result));
        }

    }
}
